<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="用户名称">
                <a-input placeholder="请输入用户名称" v-model="queryParam.name" allowClear></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="手机号码">
                <a-input placeholder="请输入手机号码" v-model="queryParam.tel" allowClear></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="车牌号">
                <div class="flex">
                  <a-input class="inp" placeholder="请输入车牌号码" v-model="queryParam.car_no" allowClear></a-input>
                  <a-button type="primary" @click="getList()">查询</a-button>
                </div>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>
    <a-card :border="false">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <a-radio-group v-model="queryParam.status" @change="getList()">
          <a-radio-button value="-1"> 全部 </a-radio-button>
          <a-radio-button value="0"> 未审核 </a-radio-button>
          <a-radio-button value="1"> 已审核 </a-radio-button>
        </a-radio-group>

        <div>
          <a-button type="primary" icon="plus" @click="edit()"> 新建 </a-button>

          <a-dropdown>
            <a-menu slot="overlay">
              <a-menu-item @click="handleAll('change', '1')">批量开启</a-menu-item>
              <a-menu-item @click="handleAll('change', '0')">批量关闭</a-menu-item>
              <a-menu-item @click="handleAll('change', '2')">批量删除</a-menu-item>
            </a-menu>
            <a-button> 批量操作 </a-button>
          </a-dropdown>
        </div>
      </div>

      <a-table
        :rowSelection="{ selectedRowKeys: this.selectedRowKeys, onChange: this.onSelectChange }"
        size="default"
        :columns="columns"
        :data-source="list"
        :row-key="(record) => record.id"
        :pagination="{
          total: this.total,
          pageSize: this.pageSize,
          showSizeChanger: false,
          onChange: this.tablePageChange,
        }"
        :scroll="{ x: 'max-content' }"
      >
        <span slot="content" slot-scope="text, record">
          <div class="content" v-if="record.saas_user">
            <div class="img">
              <a-avatar shape="square" :size="48" icon="user" :src="record.saas_user.avatar" />
            </div>

            <div class="txt">
              <h3>{{ record.saas_user.name }}</h3>
              <p>{{ record.saas_user.mobile }}</p>
            </div>
          </div>
        </span>

        <span slot="status" slot-scope="text, record">
          <a-badge :color="getStatus(record.status)[1]" :text="getStatus(record.status)[0]" />
        </span>

        <span slot="created_at" slot-scope="text, record">
          {{ record.created_at > 0 ? $moment(record.created_at * 1000).format('YYYY-MM-DD HH:mm:ss') : '-' }}
        </span>

        <span slot="action" slot-scope="text, record">
          <a-button type="link" size="small" @click="edit(record)">编辑</a-button>
          <a-divider type="vertical" />
          <a-dropdown>
            <a-menu slot="overlay">
              <a-menu-item v-if="record.status === '0'"
                ><a href="javascript:;" @click="handleItem('change', record, '1')">开启</a></a-menu-item
              >
              <a-menu-item v-if="record.status === '1'">
                <a href="javascript:;" @click="handleItem('change', record, '0')">关闭</a>
              </a-menu-item>
              <a-menu-item>
                <a href="javascript:;" @click="handleItem('change', record, '2')">删除</a>
              </a-menu-item>
            </a-menu>
            <a class="ant-dropdown-link"> 更多 <a-icon type="down" /> </a>
          </a-dropdown>
        </span>
      </a-table>

      <a-modal
        :loading="modalLoading"
        :title="form.id ? '编辑司机' : '新增司机'"
        :visible="visible"
        @ok="submitForm"
        width="700px"
        @cancel="visible = false"
      >
        <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }">
          <a-form-model-item label="线路名称" prop="line_name">
            <a-input placeholder="请输入线路名称" v-model="form.line_name" allowClear></a-input>
          </a-form-model-item>
          <a-form-model-item label="绑定用户" prop="saas_user_id">
            <div class="flex">
              <a-input class="inp" disabled placeholder="请选择用户" :value="saas_user_name"></a-input>
              <a-button type="primary" @click="$refs['selectUser'].visible = true"> 选择 </a-button>
            </div>
          </a-form-model-item>
          <a-form-model-item label="真实姓名" prop="name">
            <a-input placeholder="请输入真实姓名" v-model="form.name" allowClear></a-input>
          </a-form-model-item>
          <a-form-model-item label="手机号" prop="tel">
            <a-input placeholder="请输入手机号" v-model="form.tel" allowClear></a-input>
          </a-form-model-item>
          <a-form-model-item label="车牌号码" prop="car_no">
            <a-input placeholder="请输入车牌号码" v-model="form.car_no" allowClear></a-input>
          </a-form-model-item>

          <a-form-model-item label="是否开启" prop="status">
            <a-radio-group v-model="form.status">
              <a-radio :value="1"> 开启 </a-radio>
              <a-radio :value="0"> 关闭 </a-radio>
            </a-radio-group>
            <div class="tip">用于司机在配送端登录</div>
          </a-form-model-item>
          <a-form-model-item label="配送区域" required>
            <MapPolygon v-if="visible" :area="area" ref="MapPolygon" @ok="setMap"></MapPolygon>
          </a-form-model-item>
        </a-form-model>
      </a-modal>

      <selectUser ref="selectUser" @select="select"></selectUser>
    </a-card>
  </page-header-wrapper>
</template>
<script>
import MapPolygon from './components/MapPolygon'
import { driverStatus, districtList, driverSave } from '@/api/driver'
import selectUser from '@/components/SelectUser/newSelectUser'

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 100,
  },
  {
    title: '用户信息',
    scopedSlots: {
      customRender: 'content',
    },
    width: 200,
  },
  {
    title: '线路名称',
    dataIndex: 'line_name',
  },
  {
    title: '真实姓名',
    dataIndex: 'name',
  },
  {
    title: '车牌号',
    dataIndex: 'car_no',
  },
  {
    title: '司机状态',
    scopedSlots: {
      customRender: 'status',
    },
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    scopedSlots: {
      customRender: 'created_at',
    },
    sorter: (a, b) => a.created_at - b.created_at,
  },
  {
    title: '操作',
    scopedSlots: {
      customRender: 'action',
    },
  },
]
export default {
  components: {
    selectUser,
    MapPolygon,
  },

  data() {
    return {
      total: 0,
      pageNo: 1,
      pageSize: 10,
      columns,

      queryParam: {
        name: '',
        mobile: '',
        status: '-1',
        car_no: '',
      },
      list: [],

      saas_user_name: '',
      form: {
        line_name: '',
        saas_user_id: '',
        tel: '',
        name: '',
        car_no: '',
        status: 1,
        area: [],
      },

      rules: {
        line_name: [{ required: true, message: '线路名称不能为空', trigger: 'blur' }],
        tel: [{ required: true, message: '手机号不能为空', trigger: 'blur' }],
        saas_user_id: [{ required: true, message: '用户不能为空', trigger: 'change' }],
        name: [{ required: true, message: '真实姓名不能为空', trigger: 'blur' }],
        car_no: [{ required: true, message: '车牌号码不能为空', trigger: 'blur' }],
        status: [{ required: true, message: '请选择', trigger: 'change' }],
      },
      modalLoading: false,
      visible: false,
      selectedRowKeys: [],

      area: [],
    }
  },

  mounted() {
    this.getList()
  },

  computed: {
    getStatus() {
      return (status) => {
        let text, color
        switch (status) {
          case '0':
            text = '未开启'
            color = 'rgba(0, 0, 0, 0.25)'
            break

          case '1':
            text = '已开启'
            color = '#65C817'
            break
        }
        return [text, color]
      }
    },
  },

  methods: {
    // 表单提交
    submitForm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let { form } = this
          this.modalLoading = true
          driverSave(form)
            .then((res) => {
              this.modalLoading = false
              if (res.code !== 0) {
                this.$error({
                  content: res.msg,
                })
              } else {
                this.$message.success(res.msg)
                this.visible = false
                this.area = []
                this.getList()
              }
            })
            .catch((err) => {
              this.$message.error(err.message)
              this.modalLoading = false
            })
        }
      })
    },

    edit(item) {
      if (item) {
        this.form = {
          id: item.id,
          line_name: item.line_name,
          saas_user_id: item.saas_user_id,
          tel: item.tel,
          name: item.name,
          car_no: item.car_no,
          status: parseInt(item.status),
          area: JSON.parse(item.area),
        }

        this.area = JSON.parse(item.area)
        this.saas_user_name = item.saas_user.name
        this.visible = true
        return
      }

      this.area = []
      this.visible = true
    },

    // 获取数据列表
    async getList(pageNo = 1) {
      const hide = this.$message.loading('加载中', 0)
      let { queryParam, pageSize } = this

      const res = await districtList({
        ...queryParam,
        pageSize,
        pageNo,
      })
      if (res.code == 0) {
        console.log('res,', res)
        this.selectedRowKeys = []
        let { totalCount, list } = res.data
        this.total = totalCount
        this.list = list
      }
      hide()
    },

    // 分页请求
    tablePageChange(e) {
      this.getList(e)
    },

    // 选中多行
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },

    // 批量操作
    handleAll(type, status) {
      let { selectedRowKeys } = this
      if (!selectedRowKeys.length) {
        this.$message.error('请至少选择一条数据~')
        return
      }

      switch (type) {
        case 'change':
          this.changeStatus(selectedRowKeys.join(','), status)
          break
      }
    },

    // 点击单个
    handleItem(type, item, status) {
      switch (type) {
        case 'change':
          this.changeStatus(item.id, status)
          break
      }
    },

    // 修改状态
    changeStatus(ids, status) {
      driverStatus({
        ids,
        status,
      }).then((res) => {
        if (res.code !== 0) {
          this.$error({
            content: res.msg,
          })
        } else {
          this.$message.success(res.msg)
          this.getList()

          this.selectedRowKeys = []
        }
      })
    },

    select({ name, id, mobile: tel }) {
      this.saas_user_name = name
      this.form.saas_user_id = id
      this.form.tel = tel
    },

    setMap(e) {
      let area = []
      if (e.length) {
        area = e.map((el) => {
          el.paths = el.paths.map((ce) => {
            let { lat, lng } = ce
            return [lng, lat]
          })

          return el.paths
        })
      }

      this.form.area = area
    },
  },
}
</script>

<style lang="less" scoped>
.searchBox {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  padding: 8px 0 18px 0;
  /deep/ .ant-input-affix-wrapper {
    width: 220px;
    margin-right: 20px;
  }
  .select {
    display: flex;
    align-items: center;
    margin-right: 20px;
  }
}

.content {
  display: flex;
  align-items: center;
  height: 48px;
  max-width: 300px;
  overflow: hidden;

  .txt {
    margin-left: 16px;
    flex: 1;
    overflow: hidden;

    * {
      margin: 0;
      font-size: 14px;
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
    }

    h3 {
      color: rgba(0, 0, 0, 0.85);
    }

    p {
      color: rgba(0, 0, 0, 0.45);
    }
  }
}

.flex {
  display: flex;

  .inp {
    margin-right: 20px;
  }
}
</style>
